import { useImmer } from "use-immer";
import { TaskOrderStatus } from "@/apis/__generated/model/enums";
import { Dictionaries } from "@/apis/__generated/model/enums/DictConstants";
import { usePageHelper } from "@/hook";
import { api } from "@/utils/api-instance";
import Taro from "@tarojs/taro";
import { View } from "@tarojs/components";
import { Button, Empty, TabPane, Tabs } from "@nutui/nutui-react-taro";
import OrderRow from "@/pages/index/components/order-row";
import { TaskOrderDto } from "@/apis/__generated/model/dto";
import "./order-list.scss";

export default function DeliverOrderList() {
  const [activeStatus, setActiveStatus] =
    useImmer<TaskOrderStatus>("TO_BE_ACCEPT");
  const { TO_BE_ACCEPT, TO_BE_DELIVERED, FINISHED } =
    Dictionaries.TaskOrderStatus;
  const tabList = [TO_BE_ACCEPT, TO_BE_DELIVERED, FINISHED];

  const handleTabChange = async (status: TaskOrderStatus) => {
    setActiveStatus(status);
    await reloadPageData({ query: { status: status } });
  };
  const { dataList, reloadPageData } = usePageHelper(
    api.taskOrderForFrontController.queryForDeliver,
    api.taskOrderForFrontController,
    { query: { status: activeStatus } },
  );
  const handleCancel = async (id: string) => {
    Taro.showModal({
      title: "是否确认取消订单",
      success: (actionRes) => {
        if (actionRes.confirm) {
          Taro.showLoading();
          api.taskOrderForFrontController
            .acceptedCancelForDeliver({ id })
            .then(() => {
              Taro.showToast({
                title: "取消成功",
                icon: "success",
              });
              Taro.hideLoading();
              reloadPageData();
            });
        }
      },
    });
  };
  const handleDeliver = (id: string) => {
    Taro.showLoading();
    api.taskOrderForFrontController.deliver({ id }).then(() => {
      reloadPageData();
      Taro.hideLoading();
    });
  };
  const handleConfirm = (id: string) => {
    Taro.showLoading();
    api.taskOrderForFrontController.confirm({ id }).then(() => {
      reloadPageData();
      Taro.hideLoading();
    });
  };
  const handlePhoneCall = (phoneNumber: string) => {
    Taro.makePhoneCall({
      phoneNumber,
    });
  };
  const toBeDeliveredButtons = (
    order: TaskOrderDto["TaskOrderRepository/COMPLEX_FETCHER_FOR_FRONT"],
  ) => {
    return order.status == "TO_BE_DELIVERED"
      ? [
          <Button
            size="small"
            plain
            key={1}
            onClick={() => handleCancel(order.id)}
          >
            取消订单
          </Button>,
          <Button
            size="small"
            key={3}
            type="info"
            onClick={() => handlePhoneCall(order.sourceAddress.phoneNumber)}
          >
            联系对方
          </Button>,
          <Button
            key={2}
            size="small"
            type="success"
            onClick={() => handleConfirm(order.id)}
          >
            确认送达
          </Button>,
        ]
      : [];
  };
  const toBeAcceptedButtons = (
    order: TaskOrderDto["TaskOrderRepository/COMPLEX_FETCHER_FOR_FRONT"],
  ) => {
    return order.status == "TO_BE_ACCEPT" ? (
      <Button
        size="small"
        type="success"
        plain
        key={1}
        onClick={() => handleDeliver(order.id)}
      >
        立即接单
      </Button>
    ) : (
      <View></View>
    );
  };

  return (
    <View className="order-list">
      <Tabs className="tabs" value={activeStatus} onChange={handleTabChange}>
        {tabList.map((tab) => {
          return (
            <TabPane
              title={tab.keyName}
              key={tab.keyEnName}
              value={tab.keyEnName}
            >
              {dataList.length ? (
                dataList.map((order) => {
                  return (
                    <View className="order" key={order.id}>
                      <OrderRow
                        order={order}
                        buttons={[
                          ...toBeDeliveredButtons(order),
                          toBeAcceptedButtons(order),
                        ]}
                      ></OrderRow>
                    </View>
                  );
                })
              ) : (
                <Empty />
              )}
            </TabPane>
          );
        })}
      </Tabs>
    </View>
  );
}
